﻿<%@ WebHandler Language="C#" Class="FinancePayed" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;
using Chenxin.Lib.Business;
using Chenxin.Lib.Business.BLL;

public class FinancePayed : AjaxHandlerBase
{

    public FinancePayed()
    {
        //生产奖金
        htTypePermit.Add("calculatebonus", Constants.Permit_FinancePayed_Calculat);
        //导出
        htTypePermit.Add("export", Constants.Permit_FinancePayed_Export);
    }
    override public void RequestProcess(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";

            string strOp = context.Request["op"];
            string strRet = string.Empty;
            switch (strOp.ToLower())
            {
                //添加报备相关信息
                case "getlist":
                    GetList(context);
                    break;
                case "getdetails":
                    GetDetails(context);
                    break;
                case "calculatebonus":
                    strRet = Calculate(context);
                    break;
                default:
                    break;
            }
            if (!string.IsNullOrEmpty(strRet))
            {
                context.Response.Write(strRet);
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }

    private string Calculate(HttpContext context)
    {
        //生产奖金
        string strModel = context.Request.Params["model"];
        int iYear = 0;
        int iMonth = 0;
        if (!string.IsNullOrEmpty(strModel))
        {
            iYear = int.Parse(strModel.Substring(12, 4));
            iMonth = int.Parse(strModel.Substring(17, 2));
        }

        //生产奖金
        Chenxin.Lib.Business.DAL.t_Personal_FinancePayedSumInfo.Proce(iYear, iMonth);
        return retExecResult(Constants.ExecResult.Succ, "生产成功！", "");
    }
    
    private void GetDetails(HttpContext context)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append(" (1=1) ");
        string datetime = context.Request["CalculateDate"];
        if (!string.IsNullOrEmpty(datetime))
        {
            string year = datetime.Substring(0, 4);
            string month = datetime.Length > 6 ? datetime.Substring(5, 2).TrimStart('0') : datetime.Substring(5, 1);
            sb.AppendFormat(" and CalculateYear='{0}' and CalculateMonth='{1}' ", year, month);
        }
        if (!string.IsNullOrEmpty(context.Request["userid"]))
        {
            sb.AppendFormat(" and  EmployeeId='{0}' ", context.Request["userid"]);
        }
        if (!string.IsNullOrEmpty(context.Request["depid"]))
        {
            sb.AppendFormat(" and  DepartId='{0}' ", context.Request["depid"]);
        }

        string strSql = "select * from t_Personal_FinancePayedDetailInfo where " + sb.ToString();
        DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);

        context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[0].Rows.Count, Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));
    }

    private void GetList(HttpContext context)
    {
        StringBuilder sb = new StringBuilder();
        //查询5级
        Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
        Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
        Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
        Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
        Guid userId = (string.IsNullOrEmpty(context.Request["UserId"])) ? Guid.Empty : new Guid(context.Request["UserId"]);

        sb.Append(" (1=1) ");
            
        if (userId != Guid.Empty)
            sb.AppendFormat(" AND EmployeeId='{0}' ", userId);
        if (departs != Guid.Empty)
        {
            sb.AppendFormat(" and DepartId='{0}' ", departs);
        }
        else if (businessdistrict != Guid.Empty)
        {
            sb.AppendFormat(" and AreaId ='{0}' ",businessdistrict);
        }
        else if (company != Guid.Empty)
        {
            sb.AppendFormat(" and CompanyId='{0}' ", company);
        }
        else if (city != Guid.Empty)
        {
            sb.AppendFormat(" and CityId='{0}'  ", city);
        }
        else
        {
            sb.AppendFormat(" and companyid='{0}' ", CurrentUserInfo.CompanyId);
        }

        string datetime = context.Request["CalculateDate"];
        if (!string.IsNullOrEmpty(datetime))
        {
            string year = datetime.Substring(0, 4);
            string month = datetime.Length > 6 ? datetime.Substring(5, 2).TrimStart('0') : datetime.Substring(5, 1);
            sb.AppendFormat(" and CalculateYear='{0}' and CalculateMonth='{1}' ", year, month);
        }

        string strSql = "select * from t_Personal_FinancePayedSumInfo where " + sb.ToString() + " order by AreaId,DepartId,EmployeeCode,ContractArchYear,ContractArchMonth";
        DataSet ds = Chenxin.Lib.Business.DAL.t_Personal_FinancePayedSumInfo.ExecSql(strSql);

        string strHTML = GetHTML(ds.Tables[0]);
    
        context.Response.Write(string.Format("{{success:1,msg:'',data:{{html:'{0}'}}}}",strHTML));
    }

    private string GetHTML(DataTable dt)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<table style=\"width:1700px;text-align: center;\" border=\"1\" ><tr class=\"x-grid-head\">");
        sb.Append("<td style=\"width:150px;\">商圈</td>");
        sb.Append("<td style=\"width:120px;\">部门</td>");
        sb.Append("<td style=\"width:120px;\">人员</td>");
        sb.Append("<td style=\"width:120px;\">工号</td>");
        
        //sb.Append("<td style=\"width:120px;\">本月实收</td>");
        //sb.Append("<td style=\"width:120px;\">实收归属</td>");
        //sb.Append("<td style=\"width:120px;\">业绩归属</td>");
        //sb.Append("<td style=\"width:220px;\">业绩归属月总实收</td>");
        //sb.Append("<td style=\"width:120px;\">前期实收</td>");
        //sb.Append("<td style=\"width:120px;\">本月奖金</td>");
        //sb.Append("<td style=\"width:120px;\">前期奖金</td>");
        //sb.Append("<td style=\"width:120px;\">总奖金</td></tr>");
        
        //-----------------------------------------------------
        sb.Append("<td style=\"width:120px;\">业绩归属</td>");
        sb.Append("<td style=\"width:120px;\">实收归属</td>");
        sb.Append("<td style=\"width:120px;\">本月实收</td>");
        sb.Append("<td style=\"width:120px;\">前期实收</td>");
        sb.Append("<td style=\"width:220px;\">业绩归属月总实收</td>");
        sb.Append("<td style=\"width:120px;\">当月基数</td>");
        sb.Append("<td style=\"width:120px;\">前期基数</td>");
        sb.Append("<td style=\"width:120px;\">总基数</td>");
        sb.Append("<td style=\"width:120px;\">本月奖金</td>");
        sb.Append("<td style=\"width:120px;\">前期奖金</td>");
        sb.Append("<td style=\"width:120px;\">总奖金</td></tr>");
        //-----------------------------------------------------

        string userid = "";
        string depid = "";
        string areaid = "";
        decimal user_count1 = 0;  //个人本月实收 汇总
        decimal user_count2 = 0;  //个人本月奖金 汇总
        decimal dep_count1 = 0;  //个人本月实收 汇总
        decimal dep_count2 = 0;  //个人应发奖金 汇总
        decimal area_count1 = 0;  //个人本月实收 汇总
        decimal area_count2 = 0;  //个人应发奖金 汇总
        decimal count1 = 0;  //个人本月实收 汇总
        decimal count2 = 0;//个人应发奖金 汇总
        decimal count3 = 0;
        decimal user_count3 = 0;    //个人本月基数
        decimal dep_count3 = 0;
        decimal area_count3 = 0;

        string temp_areaid = "";
        string temp_depid = "";
        string temp_userid = "";
        
        for (int i = 0; i < dt.Rows.Count;i++ )
        {
            
            DataRow dr = dt.Rows[i];            
            areaid = DatasetHelper.GetValue(dr, "AreaId", "").ToString();
            depid = DatasetHelper.GetValue(dr, "DepartId", "").ToString();
            userid = DatasetHelper.GetValue(dr, "EmployeeId", "").ToString();

            sb.Append("<tr style=\"text-align: center;\" class=\"x-grid-row\">");
            //合并商圈
            if (temp_areaid != areaid)
            {
                DataRow[] arealist = dt.Select("AreaId='" + areaid + "'");
                sb.AppendFormat("<td rowspan=\"{0}\" style=\"width:150px;text-align: center;\">{1}</td>", arealist.Length + GetRowCount(10, areaid, "area", dt) + GetRowCount(20, areaid, "area", dt), DatasetHelper.GetValue(dt.Rows[i], "AreaName", ""));
                temp_areaid = areaid;
            }
            //合并部门
            if (temp_depid != depid)
            {
                DataRow[] deplist = dt.Select("DepartId='" + depid + "' and AreaId='" + areaid + "'");
                sb.AppendFormat("<td rowspan=\"{0}\" style=\"width:120px;text-align: center;\">{1}</td>", deplist.Length + GetRowCount(20, depid, "dep", dt), DatasetHelper.GetValue(dt.Rows[i], "DepartName", ""));
                temp_depid = depid;
            }
            //合并员工
            if (temp_userid != userid)
            {
                DataRow[] userlist = dt.Select("EmployeeId='" + userid + "' and DepartId='" + depid + "'");
                sb.AppendFormat("<td rowspan=\"{0}\" style=\"width:120px;text-align: center;\"><a class=\"a_details\" title=\"{1}\" userid=\"{3}\" type=\"{4}\" style=\"cursor:pointer\">{1}</a></td><td rowspan=\"{0}\" style=\"width:120px;text-align: center;\">{2}</td>", userlist.Length, DatasetHelper.GetValue(dt.Rows[i], "EmployeeName", ""), DatasetHelper.GetValue(dt.Rows[i], "EmployeeCode", ""), userid,depid);
                temp_userid = userid;
            }

            //sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "CurPayMoney", (decimal)0));
            //sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "PayArchYear", "") + "年" + DatasetHelper.GetValue(dr, "PayArchMonth", "") + "月");
            //sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "ContractArchYear", "") + "年" + DatasetHelper.GetValue(dr, "ContractArchMonth", "") + "月");
            //sb.AppendFormat("<td style=\"width:220px;\">{0}</td>", DatasetHelper.GetValue(dr, "TotalPayMoney", (decimal)0));
            //sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "TotalPayMoney", (decimal)0) - DatasetHelper.GetValue(dr, "CurPayMoney", (decimal)0));
            //sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "CurrentMonthBonus", (decimal)0));
            //sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "ProtophaseBonus", (decimal)0));
            //sb.AppendFormat("<td style=\"width:120px;\">{0}</td></tr>", DatasetHelper.GetValue(dr, "TotalBonus", (decimal)0));
            
            //----------------------------------------------------------------------------------------------------------------
            sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "ContractArchYear", "") + "年" + DatasetHelper.GetValue(dr, "ContractArchMonth", "") + "月");
            sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "PayArchYear", "") + "年" + DatasetHelper.GetValue(dr, "PayArchMonth", "") + "月");
            sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "CurPayMoney", (decimal)0));
            sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "TotalPayMoney", (decimal)0) - DatasetHelper.GetValue(dr, "CurPayMoney", (decimal)0));
            sb.AppendFormat("<td style=\"width:220px;\">{0}</td>", DatasetHelper.GetValue(dr, "TotalPayMoney", (decimal)0));
            sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "CurBase", (decimal)0));
            sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "TotalBase", (decimal)0) - DatasetHelper.GetValue(dr, "CurBase", (decimal)0));
            sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "TotalBase", (decimal)0));
            sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "CurrentMonthBonus", (decimal)0));
            sb.AppendFormat("<td style=\"width:120px;\">{0}</td>", DatasetHelper.GetValue(dr, "ProtophaseBonus", (decimal)0));
            sb.AppendFormat("<td style=\"width:120px;\">{0}</td></tr>", DatasetHelper.GetValue(dr, "TotalBonus", (decimal)0));
            //----------------------------------------------------------------------------------------------------------------

            user_count1 += DatasetHelper.GetValue(dr, "CurPayMoney", (decimal)0);
            dep_count1 += DatasetHelper.GetValue(dr, "CurPayMoney", (decimal)0);
            area_count1 += DatasetHelper.GetValue(dr, "CurPayMoney", (decimal)0);

            user_count2 += DatasetHelper.GetValue(dr, "CurrentMonthBonus", (decimal)0);
            dep_count2 += DatasetHelper.GetValue(dr, "CurrentMonthBonus", (decimal)0);
            area_count2 += DatasetHelper.GetValue(dr, "CurrentMonthBonus", (decimal)0);

            user_count3 += DatasetHelper.GetValue(dr, "CurBase", (decimal)0);
            dep_count3 += DatasetHelper.GetValue(dr, "CurBase", (decimal)0);
            area_count3 += DatasetHelper.GetValue(dr, "CurBase", (decimal)0);

            count1 += DatasetHelper.GetValue(dr, "CurPayMoney", (decimal)0);
            count2 += DatasetHelper.GetValue(dr, "CurrentMonthBonus", (decimal)0);
            count3 += DatasetHelper.GetValue(dr, "CurBase", (decimal)0);

            if ((i + 1) < dt.Rows.Count)
            {
                dr = dt.Rows[(i + 1)];
                areaid = DatasetHelper.GetValue(dr, "AreaId", "").ToString();
                depid = DatasetHelper.GetValue(dr, "DepartId", "").ToString();
                userid = DatasetHelper.GetValue(dr, "EmployeeId", "").ToString();

                //添加个人小计
                if (temp_userid != userid)
                {
                    sb.AppendFormat("<tr class=\"x-grid-row\" style=\"background-color:#E8FAFD;\"><td>个人小计</td><td></td><td></td><td></td><td>{0:f2}</td><td></td><td></td><td>{1:f2}</td><td></td><td></td><td>{2:f2}</td><td></td><td></td></tr>", user_count1, user_count3, user_count2);
                    user_count1 = (decimal)0;
                    user_count2 = (decimal)0;
                    user_count3 = (decimal)0;
                }
                //添加部门合计
                if (temp_depid != depid)
                {
                    sb.AppendFormat("<tr class=\"x-grid-row\" style=\"background-color:#E8FAFD;\"><td>部门小计</td><td></td><td></td><td></td><td></td><td>{0:f2}</td><td></td><td></td><td>{1:f2}</td><td></td><td></td><td>{2:f2}</td><td></td><td></td></tr>", dep_count1, dep_count3, dep_count2);
                    dep_count1 = (decimal)0;
                    dep_count2 = (decimal)0;
                    dep_count3 = (decimal)0;
                }
                //添加商圈合计
                if (temp_areaid != areaid)
                {
                    sb.AppendFormat("<tr class=\"x-grid-row\" style=\"background-color:#E8FAFD;\"><td>商圈小计</td><td></td><td></td><td></td><td></td><td></td><td>{0:f2}</td><td></td><td></td><td>{1:f2}</td><td></td><td></td><td>{2:f2}</td><td></td><td></td></tr>", area_count1, area_count3, area_count2);
                    area_count1 = (decimal)0;
                    area_count2 = (decimal)0;
                    area_count3 = (decimal)0;
                }
            }
            else
            {
                sb.AppendFormat("<tr class=\"x-grid-row\" style=\"background-color:#E8FAFD;\"><td>个人小计</td><td></td><td></td><td></td><td>{0:f2}</td><td></td><td></td><td>{1:f2}</td><td></td><td></td><td>{2:f2}</td><td></td><td></td></tr>", user_count1, user_count3, user_count2);
                sb.AppendFormat("<tr class=\"x-grid-row\" style=\"background-color:#E8FAFD;\"><td>部门小计</td><td></td><td></td><td></td><td></td><td>{0:f2}</td><td></td><td></td><td>{1:f2}</td><td></td><td></td><td>{2:f2}</td><td></td><td></td></tr>", dep_count1, dep_count3, dep_count2);
                sb.AppendFormat("<tr class=\"x-grid-row\" style=\"background-color:#E8FAFD;\"><td>商圈小计</td><td></td><td></td><td></td><td></td><td></td><td>{0:f2}</td><td></td><td></td><td>{1:f2}</td><td></td><td></td><td>{2:f2}</td><td></td><td></td></tr>", area_count1, area_count3, area_count2);
                sb.AppendFormat("<tr class=\"x-grid-row\" style=\"background-color:#E8FAFD;\"><td>总合计</td><td></td><td></td><td></td><td></td><td></td><td>{0:f2}</td><td></td><td></td><td>{1:f2}</td><td></td><td></td><td>{2:f2}</td><td></td><td></td></tr>", count1, count3, count2);
                user_count1 = (decimal)0;
                user_count2 = (decimal)0;
                user_count3 = (decimal)0;
                dep_count1 = (decimal)0;
                dep_count2 = (decimal)0;
                dep_count3 = (decimal)0;
                area_count1 = (decimal)0;
                area_count2 = (decimal)0;
                area_count3 = (decimal)0;
                count1 = (decimal)0;
                count2 = (decimal)0;
                count3 = (decimal)0;
            }
        }
        sb.Append("</table>");
        
        return sb.ToString();
    }

    private int GetRowCount(int index, string id, string type,DataTable dt)
    {
        //index     10:查询部门总数，20:查询人员总数
        //type      表示ID 的类型  dep/area
        
        string bs = "";
        if (index == 10)
            bs = "DepartId";
        else
            bs = "EmployeeId";
        string strSql = "";
        
        if (type == "area")
        {
            strSql = "AreaId='" + id + "'";
        }
        else if (type == "dep")
        {
            strSql = "DepartId='" + id + "'";
        }
        DataRow[] list = dt.Select(strSql);
        
        string temp = "";
        List<string> templist = new List<string>();
        foreach (DataRow dr in list)
        {
            if (temp != dr[bs].ToString())
            {
                templist.Add(temp);
                temp = dr[bs].ToString();                
            }
        }

        return templist.Count;
    }
}